<?php

namespace Wechat\Controller;

class ProductController extends CommonController {

    public function share() {

        $id = $_REQUEST["id"];

        $group = D("Group")->queryById($id);
        if(isNullOrEmpty($group)) {
            $this->redirect(U("Index/index"));
        }

        $round = D("Round")->queryById($group["round_id"]);
        if(isNullOrEmpty($round)) {
            $this->redirect(U("Index/index"));
        }

        $product = D("Product")->queryById($round["product_id"]);
        if(isNullOrEmpty($product)) {
            $this->redirect(U("Index/index"));
        }

        if($group["status"] != C("GROUP_STATUS.WAITING_JOIN")) {
            $this->redirect(U("Product/index", array("id"=>$product["product_id"])));
        }

        $round["left_number"] = $product["price"]-$round["join_number"];

        $groupMemberMap["g.round_id"] = $round["round_id"];
        $groupMemberMap["gm.customer_id"] = $this->customer["customer_id"];
        $groupMemberMap["g.status"] = array("eq", C("GROUP_STATUS.WAITING_JOIN"));
        $groupMember = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($groupMemberMap)
            ->field("g.group_id")
            ->find();

        if(!isNullOrEmpty($groupMember)) {
            $this->redirect(U("Product/index", array("id"=>$product["product_id"])));
        }

        $groupCustomer = D("Customer")->queryById($group["customer_id"]);

        $groupCustomerMap["customer_id"] = $groupCustomer["customer_id"];
        $groupCustomerMap["group_id"] = $group["group_id"];
        $groupCustomer["number"] = D("GroupMember")
            ->where($groupCustomerMap)->getField("number");

        $memberList = D("GroupMember")->alias("gm")
            ->join("left join __CUSTOMER__ c on c.customer_id = gm.customer_id")
            ->where(array("gm.group_id"=>$group["group_id"]))
            ->order("gm.number desc, gm.create_time desc")
            ->field("c.nickname, c.headimgurl, gm.number, c.customer_id")
            ->limit(0, 7)
            ->select();

        $announcementMap["is_online"] = C("DEFAULT_YN.YES");
        $announcementList = D("Announcement")
            ->where($announcementMap)
            ->order("announcement_id desc")
            ->select();

        if($this->customer['subscribe'] != C('DEFAULT_YN.YES')) {
            S("sub_".$this->customer['openid'],serialize(array('browse_type'=>C('BROWSE_TYPE.SHARE'),'target_id'=>$id)),3600);
        }

        $this->assign("groupCustomer", $groupCustomer);
        $this->assign("group", $group);
        $this->assign("round", $round);
        $this->assign("product", $product);
        $this->assign("memberList", $memberList);
        $this->assign("announcementList", $announcementList);
        $this->assign("subscribe",$this->customer['subscribe']);
        $this->assign("signature",signature());
        $this->assign("appid",C('appid'));
        $this->assign("shareUrl",'http://'.$_SERVER['HTTP_HOST'].U('Product/share',array('id' => $id)));

        $this->display("share");

    }

    public function index() {

        $id = $_REQUEST["id"];

        $product = D("Product")->queryById($id);

        if(isNullOrEmpty($product)) {
            $this->redirect(U("Index/index"));
        }

        $roundMap["product_id"] = $id;
        $roundMap["status"] = C("ROUND_STATUS.WAITING");
        $round = D("Round")->where($roundMap)->find();
        $round["left_number"] = $product["price"]-$round["join_number"];

        if(isNullOrEmpty($round)) {
            $this->redirect(U("Index/index"));
        }

        $groupMemberMap["g.round_id"] = $round["round_id"];
        $groupMemberMap["gm.customer_id"] = $this->customer["customer_id"];
        $groupMemberMap["g.status"] = array("eq", C("GROUP_STATUS.WAITING_JOIN"));
        $groupMember = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($groupMemberMap)
            ->field("g.group_id")
            ->find();

        if(isNullOrEmpty($groupMember)) {
            $this->redirect(U("Product/join", array("id"=>$id)));
        }

        $group = D("Group")->queryById($groupMember["group_id"]);

        //如果未支付，作废掉
        if($group["status"] == C("GROUP_STATUS.WAITING_PAY")) {

            //作废团
            $group["status"] = C("GROUP_STATUS.SYSTEM_ABANDON");
            D("Group")->updateInfo($group);

            //作废订单
            $orderMap["customer_id"] = $this->customer["customer_id"];
            $orderMap["round_id"] = $group["round_id"];
            $order = D("Order")->queryByMap($orderMap);

            $order["status"] = C("ORDER_STATUS.SYSTEM_ABANDON");
            D("Order")->updateInfo($order);

            $this->redirect(U("Product/join", array("id"=>$id)));

        }

        $groupCustomer = D("Customer")->queryById($group["customer_id"]);

        $groupCustomerMap["customer_id"] = $groupCustomer["customer_id"];
        $groupCustomerMap["group_id"] = $group["group_id"];
        $groupCustomer["number"] = D("GroupMember")
            ->where($groupCustomerMap)->getField("number");

        $memberList = D("GroupMember")->alias("gm")
            ->join("left join __CUSTOMER__ c on c.customer_id = gm.customer_id")
            ->where(array("gm.group_id"=>$group["group_id"]))
            ->order("gm.number desc, gm.create_time desc")
            ->field("c.nickname, c.headimgurl, gm.number, c.customer_id")
            ->limit(0, 7)
            ->select();

        $announcementMap["is_online"] = C("DEFAULT_YN.YES");
        $announcementList = D("Announcement")
            ->where($announcementMap)
            ->order("announcement_id desc")
            ->select();

        if($this->customer['subscribe'] != C('DEFAULT_YN.YES')) {
            S("sub_".$this->customer['openid'],serialize(array('browse_type'=>C('BROWSE_TYPE.PRODUCT'),'target_id'=>$id)),3600);
        }

        $this->assign("groupCustomer", $groupCustomer);
        $this->assign("group", $group);
        $this->assign("round", $round);
        $this->assign("product", $product);
        $this->assign("memberList", $memberList);
        $this->assign("announcementList", $announcementList);
        $this->assign("signature",signature());
        $this->assign("appid",C('appid'));
        $this->assign("shareUrl",'http://'.$_SERVER['HTTP_HOST'].U('Product/share',array('id' => $groupMember['group_id'])));
        $this->assign("subscribe",$this->customer['subscribe']);
        $this->display("index");

    }

    public function join() {

        $id = $_REQUEST["id"];

        $product = D("Product")->queryById($id);

        if(isNullOrEmpty($product)) {
            $this->redirect(U("Index/index"));
        }

        $roundMap["product_id"] = $id;
        $roundMap["status"] = C("ROUND_STATUS.WAITING");
        $round = D("Round")->where($roundMap)->find();
        $round["left_number"] = $product["price"]-$round["join_number"];

        if(isNullOrEmpty($round)) {
            $this->redirect(U("Index/index"));
        }

        $groupMemberMap["g.round_id"] = $round["round_id"];
        $groupMemberMap["gm.customer_id"] = $this->customer["customer_id"];
        $groupMemberMap["g.status"] = array("eq", C("GROUP_STATUS.WAITING_JOIN"));
        $groupMember = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($groupMemberMap)
            ->field("g.group_id")
            ->find();

        if(!isNullOrEmpty($groupMember)) {
            $this->redirect(U("Product/index", array("id"=>$id)));
        }

        $announcementMap["is_online"] = C("DEFAULT_YN.YES");
        $announcementList = D("Announcement")
            ->where($announcementMap)
            ->order("announcement_id desc")
            ->select();

        if($this->customer['subscribe'] != C('DEFAULT_YN.YES')) {
            S("sub_".$this->customer['openid'],serialize(array('browse_type'=>C('BROWSE_TYPE.JOIN'),'target_id'=>$id)),3600);
        }

        $this->assign("round", $round);
        $this->assign("product", $product);
        $this->assign("announcementList", $announcementList);
        $this->assign("subscribe",$this->customer['subscribe']);
        $this->assign("signature",signature());
        $this->assign("appid",C('appid'));
        $this->assign("shareUrl",'http://'.$_SERVER['HTTP_HOST'].U('Product/join',array('id' => $id)));

        $this->display("join");

    }

    public function groupMemberList() {

        $groupId = I("post.groupId");
        $pageNum = I("post.pageNum") ? I("post.pageNum") : 2;

        $index = ($pageNum-1)*8 - 1;

        $memberList = D("GroupMember")->alias("gm")
            ->join("left join __CUSTOMER__ c on c.customer_id = gm.customer_id")
            ->where(array("gm.group_id"=>$groupId))
            ->order("gm.number desc, gm.create_time desc")
            ->field("c.nickname, c.headimgurl, gm.number, c.customer_id")
            ->limit($index, 8)
            ->select();

        echo json_encode($memberList);

    }

    public function waitingGroup() {

        $id = $_REQUEST["id"];

        $round = D("Round")->queryById($id);

        if(isNullOrEmpty($round)) {
            $this->redirect(U("Index/index"));
        }

        $product = D("Product")->queryById($round['product_id']);

        if(isNullOrEmpty($product)) {
            $this->redirect(U("Index/index"));
        }

        $round["left_number"] = $product["price"]-$round["join_number"];

        $bannerMap["banner_type"] = C("BANNER_TYPE.PRODUCT");
        $bannerMap["is_online"] = C("DEFAULT_YN.YES");
        $bannerList = D("Banner")
            ->where($bannerMap)->select();

        $announcementMap["is_online"] = C("DEFAULT_YN.YES");
        $announcementList = D("Announcement")
            ->where($announcementMap)
            ->order("announcement_id desc")
            ->select();

        $this->assign("announcementList", $announcementList);
        $this->assign("bannerList", $bannerList);
        $this->assign("round",$round);
        $this->assign("product",$product);

        $this->display("waitingGroup");

    }

    public function waitingList() {

        $data["code"] = 200;

        $id = I("post.id");
        $pageNum = I("post.pageNum") ? I("post.pageNum") : 1;

        $product = D("Product")->queryById($id);

        if(isNullOrEmpty($product)) {
            $data["code"] = -1;
            $data["msg"] = "对不起，未找到该商品";
            echo json_encode($data);
            exit();
        }

        $roundMap["product_id"] = $id;
        $roundMap["status"] = C("ROUND_STATUS.WAITING");
        $round = D("Round")->where($roundMap)->find();

        if(isNullOrEmpty($round)) {
            $data["code"] = -2;
            $data["msg"] = "对不起，未找到该轮购买";
            echo json_encode($data);
            exit();
        }

        $groupMap["g.status"] = C("GROUP_STATUS.WAITING_JOIN");
        $groupMap["g.round_id"] = $round['round_id'];
        $groupList = D("Group")->alias('g')
                ->join("LEFT JOIN __ROUND__ r on r.round_id = g.round_id")
                ->join("LEFT JOIN __CUSTOMER__ c ON g.customer_id = c.customer_id")
                ->field("r.product_id, c.customer_id, 
                    c.nickname, c.headimgurl, g.group_id, 
                    g.member_number, g.buy_number")
                ->where($groupMap)
                ->order("g.buy_number DESC")
                ->limit(($pageNum-1)*C("DEFAULT_PAGE_SIZE"), C("DEFAULT_PAGE_SIZE"))
                ->select();

        foreach ($groupList as &$group) {
            $memberMap['group_id'] = $group['group_id'];
            $group['member_list'] = D('GroupMember')->alias('gm')
                ->join('LEFT JOIN __CUSTOMER__ c ON gm.customer_id = c.customer_id')
                ->field("c.customer_id, c.headimgurl, IF(gm.customer_id = " .$group['customer_id']. ",1,0) AS is_leader")
                ->where($memberMap)
                ->order("is_leader DESC, number DESC")
                ->limit(8)
                ->select();
        }

        $data['group_list'] = $groupList;

        echo json_encode($data);

    }

    public function winGroup() {

        $id = $_REQUEST["id"];

        $round = D("Round")->queryById($id);

        if(isNullOrEmpty($round)) {
            $this->redirect(U("Index/index"));
        }

        $product = D("Product")->queryById($round['product_id']);

        if(isNullOrEmpty($product)) {
            $this->redirect(U("Index/index"));
        }

        $round["left_number"] = $product["price"]-$round["join_number"];

        $bannerMap["banner_type"] = C("BANNER_TYPE.PRODUCT");
        $bannerMap["is_online"] = C("DEFAULT_YN.YES");
        $bannerList = D("Banner")
            ->where($bannerMap)->select();

        $announcementMap["is_online"] = C("DEFAULT_YN.YES");
        $announcementList = D("Announcement")
            ->where($announcementMap)
            ->order("announcement_id desc")
            ->select();

        $this->assign("announcementList", $announcementList);
        $this->assign("bannerList", $bannerList);
        $this->assign("round",$round);
        $this->assign("product",$product);

        $this->display("winGroup");

    }

    public function winList() {

        $data["code"] = 200;

        $id = I("post.id");
        $pageNum = I("post.pageNum") ? I("post.pageNum") : 1;

        $product = D("Product")->queryById($id);

        if(isNullOrEmpty($product)) {
            $data["code"] = -1;
            $data["msg"] = "对不起，未找到该商品";
            echo json_encode($data);
            exit();
        }

        $groupMap['r.product_id'] = $id;
        $groupMap['r.status'] = C("ROUND_STATUS.END");
        $groupMap["g.status"] = C("GROUP_STATUS.WIN");
        $groupList = D('Round')->alias('r')
                ->join('LEFT JOIN __GROUP__ g ON r.round_id = g.round_id')
                ->join('LEFT JOIN __CUSTOMER__ c ON g.customer_id = c.customer_id')
                ->field('r.round_index,r.round_id, c.customer_id, c.nickname, c.headimgurl, 
                    g.group_id, g.member_number, g.buy_number, g.reward')
                ->where($groupMap)
                ->order("g.create_time DESC,g.buy_number DESC")
                ->limit(($pageNum-1)*C("DEFAULT_PAGE_SIZE"), C("DEFAULT_PAGE_SIZE"))
                ->select();

        foreach ($groupList as &$group) {
            $memberMap['gm.group_id'] = $group['group_id'];
            $group['member_list'] = D('GroupMember')->alias('gm')
                ->join('LEFT JOIN __CUSTOMER__ c ON gm.customer_id = c.customer_id')
                ->field("c.customer_id, c.headimgurl, IF(gm.customer_id = " .$group['customer_id']. ",1,0) AS is_leader")
                ->where($memberMap)
                ->order("is_leader DESC, gm.number DESC")
                ->limit(4)
                ->select();

            $countMap['round_id'] = $group['round_id'];
            $countMap['status'] = C('GROUP_STATUS.FAILURE');
            $group['failure_count'] = D('Group')->where($countMap)->count();
        }

        $data['group_list'] = $groupList;

        echo json_encode($data);

    }

    public function failureGroup() {

        $id = $_REQUEST["id"];

        $round = D("Round")->queryById($id);

        if(isNullOrEmpty($round)) {
            $this->redirect(U("Index/index"));
        }

        $product = D("Product")->queryById($round['product_id']);

        if(isNullOrEmpty($product)) {
            $this->redirect(U("Index/index"));
        }

        $round["left_number"] = $product["price"]-$round["join_number"];

        $bannerMap["banner_type"] = C("BANNER_TYPE.PRODUCT");
        $bannerMap["is_online"] = C("DEFAULT_YN.YES");
        $bannerList = D("Banner")
            ->where($bannerMap)->select();

        $announcementMap["is_online"] = C("DEFAULT_YN.YES");
        $announcementList = D("Announcement")
            ->where($announcementMap)
            ->order("announcement_id desc")
            ->select();

        $this->assign("announcementList", $announcementList);
        $this->assign("bannerList", $bannerList);
        $this->assign("round",$round);
        $this->assign("product",$product);

        $this->display("failureGroup");

    }

    public function failureList() {

        $data["code"] = 200;

        $id = I("post.id");
        $pageNum = I("post.pageNum") ? I("post.pageNum") : 1;

        $product = D("Product")->queryById($id);

        if(isNullOrEmpty($product)) {
            $data["code"] = -1;
            $data["msg"] = "对不起，未找到该商品";
            echo json_encode($data);
            exit();
        }

        $groupMap['r.product_id'] = $id;
        $groupMap['r.status'] = C("ROUND_STATUS.END");
        $groupMap["g.status"] = C("GROUP_STATUS.FAILURE");
        $groupList = D('Round')->alias('r')
            ->join('LEFT JOIN __GROUP__ g ON r.round_id = g.round_id')
            ->join('LEFT JOIN __CUSTOMER__ c ON g.customer_id = c.customer_id')
            ->field('r.round_index,c.customer_id, c.nickname, c.headimgurl, g.group_id, g.member_number, g.buy_number')
            ->where($groupMap)
            ->order("g.create_time DESC,g.buy_number DESC")
            ->limit(($pageNum-1)*C("DEFAULT_PAGE_SIZE"), C("DEFAULT_PAGE_SIZE"))
            ->select();

        foreach ($groupList as &$group) {
            $memberMap['gm.group_id'] = $group['group_id'];
            $group['member_list'] = D('GroupMember')->alias('gm')
                ->join('LEFT JOIN __CUSTOMER__ c ON gm.customer_id = c.customer_id')
                ->field("c.customer_id, c.headimgurl, IF(gm.customer_id = " .$group['customer_id']. ",1,0) AS is_leader")
                ->where($memberMap)
                ->order("is_leader DESC, gm.number DESC")
                ->limit(4)
                ->select();
        }

        $data['group_list'] = $groupList;

        echo json_encode($data);

    }

    public function winDetail() {
        $id = $_REQUEST['id'];

        $group = D('Group')->queryById($id);
        $round = D("Round")->queryById($group["round_id"]);

        $product = D("Product")->queryById($round["product_id"]);

        if(isNullOrEmpty($group)) {
            $this->redirect(U("Index/index"));
        }

        $winner = D("Customer")->alias("c")
            ->join("left join __GROUP_MEMBER__ gm 
                on gm.customer_id = c.customer_id")
            ->where(array(
                "gm.customer_id" => $round["winner_customer_id"],
                "gm.group_id" =>$group["group_id"]
            ))->field("c.customer_id,c.headimgurl,c.nickname,gm.number,gm.reward")
            ->find();
        $groupCustomer = D("Customer")->alias("c")
            ->join("left join __GROUP_MEMBER__ gm 
                on gm.customer_id = c.customer_id")
            ->where(array(
                "gm.customer_id" => $group["customer_id"],
                "gm.group_id" =>$group["group_id"]
            ))->field("c.headimgurl,c.nickname,gm.number,gm.reward")
            ->find();

        $recordList = D("OrderRecord")->alias("r")
            ->join("left join __ORDER__ o on o.order_id = r.order_id")
            ->join("left join __CUSTOMER__ c on c.customer_id = o.customer_id")
            ->where(array(
                "o.round_id" => $round["round_id"]
            ))->order("r.order_code desc")
            ->field("c.nickname,r.create_time,r.time_code")
            ->limit(5)
            ->select();

        $totalNumber = 0;

        foreach($recordList as &$record) {
            $hourDetail = substr($record["create_time"], -8);
            $timeDetail = substr($record["time_code"], -3);

            $record["time"] = $hourDetail.":".$timeDetail;
            $totalNumber += $record["time_code"];
        }

        $leftNumber = $totalNumber%$product["price"];

        $rax = 1;

        if($round["pie_type"] == C("PIE_TYPE.CASH")) {
            $rax = C("DEFAULT_REWARD_FEE");
        }

        $this->assign("rax", $rax);
        $this->assign("round", $round);
        $this->assign("recordList", $recordList);
        $this->assign("sameCustomer",
            $group["customer_id"] === $winner["customer_id"]);
        $this->assign("totalNumber", $totalNumber);
        $this->assign("leftNumber", $leftNumber);
        $this->assign("product", $product);
        $this->assign("winner", $winner);
        $this->assign("groupMember", $groupCustomer);
        $this->assign('group',$group);
        $this->display("winDetail");
    }

    public function winMemberList() {

        $pageNum = I("post.pageNum") ? I("post.pageNum") : 1;
        $groupId = I('post.id');

        $group = D('Group')->queryById($groupId);
        $round = D("Round")->queryById($group["round_id"]);

        $memberMap['gm.group_id'] = $groupId;
        $memberMap["gm.customer_id"]
            = array("not in", array(
            $group["customer_id"], $round["winner_customer_id"]
        ));
        $memberMap["gm.reward"] = array('gt',0);

        $memberList = D('Group')->alias('g')
                ->join("LEFT JOIN __GROUP_MEMBER__ gm ON g.group_id = gm.group_id")
                ->join("LEFT JOIN __CUSTOMER__ c ON gm.customer_id = c.customer_id")
                ->field("c.customer_id, c.nickname, c.headimgurl, 
                gm.number, gm.reward, IF(g.customer_id = gm.customer_id,1,0) AS is_leader")
                ->where($memberMap)
                ->order("is_leader DESC, reward DESC")
                ->limit(($pageNum-1)*C("DEFAULT_PAGE_SIZE"), C("DEFAULT_PAGE_SIZE"))
                ->select();

        if($round["pie_type"] == C("PIE_TYPE.CASH")) {
            foreach ($memberList as &$member) {
                $member["reward"] = round($member["reward"]*C("DEFAULT_REWARD_FEE"),2);
            }
        }

        echo json_encode($memberList);

    }

    //等待支付页
    public function pay() {

        $orderId = $_REQUEST['id'];

        $order = D('Order')->alias('o')
            ->join('LEFT JOIN __GROUP__ g ON o.group_id = g.group_id')
            ->join('LEFT JOIN __ROUND__ r ON g.round_id = r.round_id')
            ->join('LEFT JOIN __PRODUCT__ p ON r.product_id = p.product_id')
            ->field('o.*, p.product_name, p.image, p.price, g.buy_number')
            ->where(array('o.order_id' => $orderId))
            ->find();

        if(isNullOrEmpty($order)) {
            $this->redirect(U("Index/index"));
        }

        if($order['status'] == C('ORDER_STATUS.WAITING_PAY')) {

            $payMap['pay_id'] = $order['pay_id'];

            $pay = D('Pay')->where($payMap)->find();

            if (isNullOrEmpty($pay)) {

                $payId = D('Pay')->add(array(
                    'out_trade_no' => time() . rand(0, 999),
                    'money' => $order['number'],
                    'status' => 0,
                    'callback' => "",
                    'create_time' => getCurrentDate(),
                    'update_time' => getCurrentDate(),
                    'pay_source' => C('PAY_SOURCE.BALANCE')
                ));

                $orderData['pay_id'] = $payId;

                D('Order')->where(array('order_id' => $orderId))->save($orderData);

                $order = D('Order')->where(array('order_id' => $orderId))->find();

                $payMap['pay_id'] = $order['pay_id'];

                $pay = D('Pay')->where($payMap)->find();

            }

            //群组信息
            $groupMap['g.group_id'] = $order['group_id'];
            $group = D('Group')->alias('g')
                ->join('LEFT JOIN __ROUND__ r ON g.round_id = r.round_id')
                ->join('LEFT JOIN __CUSTOMER__ c ON g.customer_id = c.customer_id')
                ->join('LEFT JOIN __PRODUCT__ p ON r.product_id = p.product_id')
                ->field('p.product_name, p.current_round, p.image, c.customer_id, c.nickname, c.headimgurl')
                ->where($groupMap)
                ->find();

            //成员信息
            $memberMap['group_id'] = $order['group_id'];
            $memberMap['customer_id'] = $group['customer_id'];
            $member = D('GroupMember')->where($memberMap)->find();

            //支付相关
            $arr = array(
                'appid' => C('appid'),
                'mch_id' => C('mch_id'),
                'nonce_str' => $this->createNoncestr(),
                //'sign' => '',	//签名
                'body' => '去开团商品支付',
                'out_trade_no' => $pay['out_trade_no'], //订单号
                'total_fee' => $pay['money'] * 100, //金额
                //'total_fee' => 1,
                'spbill_create_ip' => get_client_ip(),
                'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Wechat/Api/WechatPay', //通知地址
                'trade_type' => 'JSAPI',
                'openid' => $this->customer['openid'],
            );

            $arr['sign'] = $this->getSign($arr);  //签名

            $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

            $arr2 = $this->xmlToArray($post);

            $jsApiObj["appId"] = C('appid');
            $timeStamp = time();
            $jsApiObj["timeStamp"] = "$timeStamp";
            $jsApiObj["nonceStr"] = $this->createNoncestr();
            $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
            $jsApiObj["signType"] = "MD5";
            $jsApiObj["paySign"] = $this->getSign($jsApiObj);

            //订单信息
            $orderDetail['description'] = 'e宝优护服务订单';
            $orderDetail['total_fee'] = $order['total_amount'] * 100;
            $orderDetail['trade_no'] = $pay['out_trade_no'];
            $orderDetail['spbill_create_ip'] = get_client_ip();
            $orderDetail['price'] = $order['total_amount'];

            $this->assign('config',$this->signature());
            $this->assign('webarr',$jsApiObj);
            $this->assign('group',$group);
            $this->assign('member',$member);
            $this->assign('balance',$this->customer['available_assets']);
            $this->assign('order',$order);
            $this->assign('orderDetail',$orderDetail);
            $this->assign('successUrl','http://'.$_SERVER['HTTP_HOST'].U('Product/paySuccess',array('id' => $orderId)));
            $this->assign('payPageType',C('PAY_PAGE_TYPE.ORDER'));

        } else if($order['status'] == C('ORDER_STATUS.WAITING_CHOOSE')) {

            $giftOrderMap['order_id'] = $orderId;
            $giftOrder = D('GiftOrder')->where($giftOrderMap)->find();

            if($giftOrder['status'] == C('DEFAULT_YN.YES')) {
                $this->redirect(U("Index/index"));
            }

            $groupMemberMap['group_id'] = $order['group_id'];
            $groupMemberMap['customer_id'] = $order['customer_id'];
            $groupMember = D('GroupMember')->where($groupMemberMap)->find();

            if(isNullOrEmpty($giftOrder)) {

                $giftOrderData['create_time'] = getCurrentDate();
                $giftOrderData['customer_id'] = $order['customer_id'];
                $giftOrderData['status'] = C('DEFAULT_YN.NO');
                $giftOrderData['order_id'] = $orderId;
                $giftOrderData['price'] = round((1 - $groupMember['number']/$order['buy_number']) * $order['price'],2);
                $giftOrderData['mobile'] = I("get.mobile");
                $giftOrderData['address'] = I("get.address");
                $giftOrderData['name'] = I("get.name");

                $giftOrderId = D('GiftOrder')->add($giftOrderData);

                $giftOrder = D('GiftOrder')->where(array('gift_order_id' => $giftOrderId))->find();

            }

            $pay = D('Pay')->where(array('pay_id' => $giftOrder['pay_id']))->find();

            if(isNullOrEmpty($pay)) {
                $payId = D('Pay')->add(array(
                    'out_trade_no' => time() . rand(0, 999),
                    'money' => $giftOrder['price'],
                    'status' => 0,
                    'callback' => '',
                    'create_time' => getCurrentDate(),
                    'update_time' => getCurrentDate(),
                    'pay_source' => C('PAY_SOURCE.WECHAT')
                ));

                $pay = D('Pay')->where(array("pay_id"=>$payId))->find();

                $giftOrderData['pay_id'] = $pay['pay_id'];
                D('GiftOrder')->where(array('gift_order_id' => $giftOrder['gift_order_id']))->save($giftOrderData);
            }

            //支付相关
            $arr = array(
                'appid' => C('appid'),
                'mch_id' => C('mch_id'),
                'nonce_str' => $this->createNoncestr(),
                //'sign' => '',	//签名
                'body' => '去开团商品支付',
                'out_trade_no' => $pay['out_trade_no'], //订单号
                'total_fee' => $pay['money'] * 100, //金额
                //'total_fee' => 1,
                'spbill_create_ip' => get_client_ip(),
                'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Wechat/Api/WechatPayGift', //通知地址
                'trade_type' => 'JSAPI',
                'openid' => $this->customer['openid'],
            );

            $arr['sign'] = $this->getSign($arr);  //签名

            $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

            $arr2 = $this->xmlToArray($post);

            $jsApiObj["appId"] = C('appid');
            $timeStamp = time();
            $jsApiObj["timeStamp"] = "$timeStamp";
            $jsApiObj["nonceStr"] = $this->createNoncestr();
            $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
            $jsApiObj["signType"] = "MD5";
            $jsApiObj["paySign"] = $this->getSign($jsApiObj);

            $this->assign('config',$this->signature());
            $this->assign('webarr',$jsApiObj);
            $this->assign('order',$order);
            $this->assign('giftOrder',$giftOrder);
            $this->assign('successUrl','http://'.$_SERVER['HTTP_HOST'].U('Order/index'));
            $this->assign('payPageType',C('PAY_PAGE_TYPE.RECEIVE'));

        }

        $this->display('pay');
    }

    /**
     * 	作用：生成签名
     */
    public function getSign($Obj) {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    /**
     * 	作用：array转xml
     */
    function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml.="<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml.="<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml.="</xml>";
        return $xml;
    }

    function signature() {
        $Obj['jsapi_ticket'] = jsapi_ticket();
        $Obj['noncestr'] = createNoncestr();
        $Obj['url'] = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $Obj['timestamp'] = time();

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        //dump($Parameters);
        $String = formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        //$String = $String."&key=".C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = sha1($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        //$Obj['signature'] = strtoupper($String);
        $Obj['signature'] = $String;

        return $Obj;
    }

    /**
     * 	作用：产生随机字符串，不长于32位
     */
    public function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str.= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 	作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 	作用：将xml转为array
     */
    public function xmlToArray($xml) {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    public function paySuccess() {

        $orderId = $_REQUEST['id'];

        $order = D('Order')->alias('o')
            ->join('LEFT JOIN __GROUP__ g ON o.group_id = g.group_id')
            ->join('LEFT JOIN __ROUND__ r ON g.round_id = r.round_id')
            ->join('LEFT JOIN __CUSTOMER__ c ON g.customer_id = c.customer_id')
            ->join('LEFT JOIN __PRODUCT__ p ON r.product_id = p.product_id')
            ->field('o.*, p.product_name, p.image, p.brief, p.price, p.end_time, c.customer_id as leader_customer_id, r.join_number')
            ->where(array('o.order_id' => $orderId))
            ->find();

        if(isNullOrEmpty($order)) {
            $this->redirect(U("Index/index"));
        }

        if($order['price'] == $order['join_number']) {
            $this->redirect(U('Order/endOrder'));
        }

        $memberMap['gm.group_id'] = $order['group_id'];
        $order['member_list'] = D('GroupMember')->alias('gm')
            ->join('LEFT JOIN __CUSTOMER__ c ON gm.customer_id = c.customer_id')
            ->field("c.customer_id, c.headimgurl, IF(gm.customer_id = " .$order['leader_customer_id']. ",1,0) AS is_leader")
            ->where($memberMap)
            ->order("is_leader DESC, gm.number DESC")
            ->limit(7)
            ->select();

        $referMap['p.show_index'] = C('DEFAULT_YN.YES');
        $referMap['r.status'] = C('ROUND_STATUS.WAITING');
        $referMap['g.status'] = C('GROUP_STATUS.WAITING_JOIN');
        $referMap['g.group_id'] = array('neq',$order['group_id']);

        $referProduct = D("Product")->alias('p')
            ->join("LEFT JOIN __ROUND__ r ON p.product_id = r.product_id")
            ->join("LEFT JOIN __GROUP__ g ON g.round_id = r.round_id")
            ->join("LEFT JOIN __CUSTOMER__ c ON g.customer_id = c.customer_id")
            ->field("p.product_id, p.price, p.product_name, p.end_time, p.image, c.customer_id, 
                    c.nickname, c.headimgurl, g.group_id, 
                    g.member_number, g.buy_number, r.join_number")
            ->where($referMap)
            ->order("g.buy_number DESC")
            ->select();

        foreach ($referProduct as &$item) {
            $referMemberMap['gm.group_id'] = $item['group_id'];
            $item['member_list'] = D('GroupMember')->alias('gm')
                ->join('LEFT JOIN __CUSTOMER__ c ON gm.customer_id = c.customer_id')
                ->field("c.customer_id, c.headimgurl, IF(gm.customer_id = " .$item['customer_id']. ",1,0) AS is_leader")
                ->where($referMemberMap)
                ->order("is_leader DESC, number DESC")
                ->limit(6)
                ->select();
        }

        $this->assign('order',$order);
        $this->assign('list',$referProduct);
        $this->assign("signature",signature());
        $this->assign("appid",C('appid'));
        $this->assign("shareUrl",'http://'.$_SERVER['HTTP_HOST'].U('Product/share',array('id' => $order['group_id'])));

        $this->display('paySuccess');
    }

    public function balancePay() {

        $data["code"] = 200;

        $orderId = I('post.orderId');

        $orderMap['order_id'] = $orderId;
        $orderMap['user_id'] = $this->customer['user_id'];

        $order = D('Order')->where($orderMap)->find();

        if(isNullOrEmpty($order)) {
            $data["code"] = -1;
            $data["msg"] = "对不起，未找到该订单！";
            echo json_encode($data);
            exit();
        }

        if($order['status'] != C('ORDER_STATUS.WAITING_PAY')) {
            $data["code"] = -2;
            $data["msg"] = "对不起，该订单状态不是待支付！";
            echo json_encode($data);
            exit();
        }

        $customer = D('Customer')->where(array('customer_id' => $order['customer_id']))->find();

        if($order['number'] > $customer['available_assets']) {
            $data["code"] = -3;
            $data["msg"] = "对不起，您的余额不足！";
            echo json_encode($data);
            exit();
        }

        $payMap['pay_id'] = $order['pay_id'];

        $pay = D('Pay')->where($payMap)->find();

        if (isNullOrEmpty($pay)) {

            $payId = D('Pay')->add(array(
                'out_trade_no' => time() . rand(0, 999),
                'money' => $order['number'],
                'status' => 1,
                'callback' => "",
                'create_time' => getCurrentDate(),
                'update_time' => getCurrentDate(),
                'pay_source' => C('PAY_SOURCE.BALANCE')
            ));

            $orderData['pay_id'] = $payId;

            D('Order')->where($orderMap)->save($orderData);

            $order = D('Order')->where($orderMap)->find();

        }

        //修改订单状态
        $orderData["status"] = C("ORDER_STATUS.WAITING_OPEN");

        D('Order')->where(array("order_id"=>$order["order_id"]))->save($orderData);

        //查找群组
        $group = D('Group')->where(array('group_id' => $order['group_id']))->find();

        //查找轮次
        $round = D('Round')->where(array('round_id' => $order['round_id']))->find();

        //查找产品
        $product = D('Product')->where(array('product_id' => $round['product_id']))->find();

        //查找群成员
        $groupMemberMap['group_id'] = $order['group_id'];
        $groupMemberMap['customer_id'] = $order['customer_id'];
        $groupMember = D('GroupMember')->where($groupMemberMap)->find();

        //判断支付用户是否为团长
        if($group['customer_id'] == $order['customer_id']) {

            if($group['status'] == C('GROUP_STATUS.WAITING_PAY')) {

                //修改团状态
                $groupStatusData['status'] = C('GROUP_STATUS.WAITING_JOIN');

                //保存群信息
                D('Group')->where(array('group_id' => $order['group_id']))->save($groupStatusData);

                //计算群数量
                $groupCountMap['round_id'] = $order['round_id'];
                $groupCountMap['status'] = C('GROUP_STATUS.WAITING_JOIN');

                $groupCount = D('Group')->where($groupCountMap)->count();

                //增加轮次中的团数量
                $roundGroupNumberData['group_number'] = $groupCount;

                //保存轮次信息
                D('Round')->where(array('round_id' => $order['round_id']))->save($roundGroupNumberData);

            } else if($group['status'] == C('GROUP_STATUS.WAITING_JOIN')) {

                //计算群购买数量
                $orderGroupSumMap['group_id'] = $order['group_id'];
                $orderGroupSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");

                $groupBuyNumber = D('Order')->where($orderGroupSumMap)->sum('number');

                //修改群信息
                $groupBuyNumberData['buy_number'] = $groupBuyNumber;

                //保存群信息
                D('Group')->where(array('group_id' => $order['group_id']))->save($groupBuyNumberData);

                //计算购买数量
                $orderMemberSumMap['group_id'] = $order['group_id'];
                $orderMemberSumMap['customer_id'] = $order['customer_id'];
                $orderMemberSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");

                $memberBuyNumber = D('Order')->where($orderMemberSumMap)->sum('number');

                //修改群成员信息
                $groupMemberData['number'] = $memberBuyNumber;
                $groupMemberData['update_time'] = getCurrentDate();

                D('GroupMember')->where(array('member_id' => $groupMember['member_id']))->save($groupMemberData);

            }

        } else {

            if(!isNullOrEmpty($groupMember)) {

                //计算购买数量
                $orderMemberSumMap['group_id'] = $order['group_id'];
                $orderMemberSumMap['customer_id'] = $order['customer_id'];
                $orderMemberSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");

                $memberBuyNumber = D('Order')->where($orderMemberSumMap)->sum('number');

                //修改群成员信息
                $groupMemberData['number'] = $memberBuyNumber;
                $groupMemberData['update_time'] = getCurrentDate();

                D('GroupMember')->where(array('member_id' => $groupMember['member_id']))->save($groupMemberData);

            } else {

                //添加群成员信息
                $groupMemberData["group_id"] = $group['group_id'];
                $groupMemberData["customer_id"] = $order['customer_id'];
                $groupMemberData["create_time"] = getCurrentDate();
                $groupMemberData["number"] = $order['number'];
                $groupMemberData["update_time"] = getCurrentDate();
                $groupMemberData["reward"] = 0;

                D("GroupMember")->add($groupMemberData);

                //计算群成员数量
                $groupMemberCountMap['group_id'] = $order['group_id'];

                $groupMemberCount = D('GroupMember')->where($groupMemberCountMap)->count();

                //增加群成员数量
                $groupMemberNumberData['member_number'] = $groupMemberCount;

                //保存群信息
                D('Group')->where(array('group_id' => $order['group_id']))->save($groupMemberNumberData);

            }

            //计算群购买数量
            $orderGroupSumMap['group_id'] = $order['group_id'];
            $orderGroupSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");

            $groupBuyNumber = D('Order')->where($orderGroupSumMap)->sum('number');

            //增加群购买数量
            $groupBuyNumberDataData['buy_number'] = $groupBuyNumber;

            //保存群信息
            D('Group')->where(array('group_id' => $order['group_id']))->save($groupBuyNumberDataData);

        }

        //计算本轮购买数量
        $orderRoundSumMap['round_id'] = $order['round_id'];
        $orderRoundSumMap['status'] = C("ORDER_STATUS.WAITING_OPEN");
        $roundJoinNumber = D('Order')->where($orderRoundSumMap)->sum('number');

        //增加轮次购买数量及进度
        $roundData['join_number'] = $roundJoinNumber;
        $roundData['progress'] = round($roundJoinNumber/$product['price'],2)*100;

        //保存轮次信息
        D('Round')->where(array('round_id' => $order['round_id']))->save($roundData);

        //todo 异步下单
        curlPost('http://114.215.113.76:9502/genOrderRecord',array('orderId' => $order['order_id']));

        //扣款
        $customerData['available_assets'] = $customer['available_assets'] - $order['number'];
        $customerData['total_assets'] = $customer['total_assets'] - $order['number'];

        D('Customer')->where(array('customer_id' => $customer['customer_id']))->save($customerData);

        //增加流水
        $accountDetailData = array('money' => -$order['number'], 'customer_id' => $order['customer_id'],
            'create_time' => getCurrentDate(), 'type' => C('ACCOUNT_DETAIL_TYPE.ORDER'), 'refer_id' => $order['order_id']);

        D('AccountDetail')->add($accountDetailData);

        //查找群组
        $group = D('Group')->where(array('group_id' => $order['group_id']))->find();

        //查找用户
        $customer = D('Customer')->where(array('customer_id' => $order['customer_id']))->find();

        //推送支付成功模板消息
        $messageData['openid'] = $customer['openid'];
        $messageData['url'] = 'http://'.$_SERVER['HTTP_HOST'].U('Order/index');
        $messageData['product_name'] = $product['product_name'];
        $messageData['order_no'] = $order['order_id'];
        $messageData['member_number'] = $group['member_number'];

        orderSuccess($messageData);

        //todo 异步推送通知
        $pushData['orderId'] = $order['order_id'];
        curlPost('http://114.215.113.76:9502/pushNotification',$pushData);

        echo json_encode($data);

    }

}